import axios from 'axios'
import store from '@/store'
import jsonBig from 'json-bigint'
const request = axios.create(
  {
    baseURL: 'http://toutiao-app.itheima.net/',
    // transformResponse 处理响应数据，默认return JSON.parse(...)
    transformResponse: [function(data) {
      try {
        return jsonBig.parse(data)
      } catch (error) {
        return {
          data
        }
      }
    }]
  }
)

request.interceptors.request.use(function(config) {
  const { token } = store.state
  if (token && token.token) {
    config.headers.Authorization = 'Bearer ' + token.token
  }
  return config
}, function(error) {
  return Promise.reject(error)
})

// response interceptor
request.interceptors.response.use(
  response => {
    // console.log(response);
    const { status } = response
    if (status === 401) {
      this.$toast.fail('token过期')
    } else {
      return response
    }
  },
  error => {
    return Promise.reject(error)
  }
)
export default request
